/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.digitalpoint.dao;

import br.com.digitalpoint.Cargo;
import br.com.digitalpoint.utils.FabricaConexao;
import java.sql.*;
/**
 *
 * @author rodrigo
 */
public class CargoDAO {
    public void incluirCargo(Cargo cargo) throws Exception{
        try{
            String insere = "INSERT INTO TBCargos (descricao) VALUES (?)";
            Connection con = FabricaConexao.abreConexao();
            PreparedStatement ps = con.prepareStatement(insere);
            //ps.setInt(1, cargo.getCodigoCargo());
            ps.setString(1, cargo.getDescricao());
            ps.execute();
        }catch(Exception e){
            throw new Exception("CargoDAO: "+e.getMessage());
        }finally{
            FabricaConexao.fechaConexao();
        }
    }

    public Cargo consultarCargo(String descricao) throws Exception{
        Cargo cargo = null;
        try{
            String consulta = "SELECT * FROM TBCargos WHERE descricao = ?";
            Connection con = FabricaConexao.abreConexao();
            PreparedStatement ps = con.prepareStatement(consulta);
            ps.setString(1, descricao);
            ResultSet resultado = ps.executeQuery();
             if (resultado.next()){
               int codigoCargo = resultado.getInt(1);
               cargo = new Cargo(codigoCargo, descricao);
            }else{
                throw new Exception("CargoDAO: Cargo não encontrado!");
            }
        }catch(Exception e){
            throw new Exception("CargoDAO:"+e.getMessage());
        }finally{
            FabricaConexao.fechaConexao();
            return cargo;
        }
    }

    public void alterarCargo(Cargo cargo) throws Exception{
        try {
            String altera = "UPDATE TBCargos SET descricao = ? WHERE cod_cargo = ?";
            Connection con = FabricaConexao.abreConexao();
            PreparedStatement ps = con.prepareStatement(altera);
            ps.setString(1, cargo.getDescricao());
            ps.setInt(2, cargo.getCodigoCargo());
            ps.execute();
        } catch (SQLException e) {
            throw new Exception("CargoDAO: "+e.getMessage());
        }finally{
            FabricaConexao.fechaConexao();
        }
    }

    public void excluirCargo(String descricao) throws Exception{
        try {
            String exclui = "DELETE FROM TBCargos WHERE descricao = ?";
            Connection con = FabricaConexao.abreConexao();
            PreparedStatement ps = con.prepareStatement(exclui);
            ps.setString(1, descricao);
            ps.execute();
        } catch (SQLException e) {
            throw new Exception("CargoDAO: "+e.getMessage());
        }finally{
            FabricaConexao.fechaConexao();
        }
    }
}
